package com.springboot_gradrecruit.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springboot_gradrecruit.common.PageResponse;
import com.springboot_gradrecruit.common.R;
import com.springboot_gradrecruit.exception.CustomException;
import com.springboot_gradrecruit.mapper.ImageMapper;
import com.springboot_gradrecruit.mapper.UserMapper;
import com.springboot_gradrecruit.model.dto.UserLoginRequest;
import com.springboot_gradrecruit.model.dto.UserLogoutRequest;
import com.springboot_gradrecruit.model.dto.UserRegisterRequest;
import com.springboot_gradrecruit.model.dto.admin.PageUserRequest;
import com.springboot_gradrecruit.model.dto.admin.UserRequest;
import com.springboot_gradrecruit.model.entity.Image;
import com.springboot_gradrecruit.model.entity.User;
import com.springboot_gradrecruit.model.vo.UserVO;
import com.springboot_gradrecruit.service.UserService;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
* @author zr
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-10-26 15:27:32
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private ImageMapper imageMapper;


    //注册
    @Override
    public UserVO register(UserRegisterRequest userRegisterRequest) {
        //1.获取参数
        String account = userRegisterRequest.getAccount();
        String password = userRegisterRequest.getPassword();
        String confirmPassword = userRegisterRequest.getConfirmPassword();
        String userName = userRegisterRequest.getUserName();
        String userRole = userRegisterRequest.getUserRole();
        //2.校验参数
        if(account==null||password==null){
            throw  new CustomException("用户名或密码不能为空");
        }
        if(!password.equals(confirmPassword)){
            throw  new CustomException("两次密码不一致");
        }
        //3.判断用户是否已经注册
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", account);
        queryWrapper.eq("user_role", userRole);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
           throw new CustomException("账号重复");
        }
        // 4. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        // 5. 插入数据
        User user = new User();
        user.setUserName(userName);
        user.setAccount(account);
        user.setPassword(encryptPassword);
        user.setUserRole(userRole);
        boolean saveResult = this.save(user);
        if (!saveResult) {
           throw new CustomException("注册失败");
        }
        //6.返回脱敏数据
        return BeanUtil.copyProperties(user, UserVO.class);
    }

    //登录
    @Override
    public UserVO login(UserLoginRequest userLoginRequest, HttpServletRequest request) {
        //1.获取参数
        String account = userLoginRequest.getAccount();
        String password = userLoginRequest.getPassword();
        String userRole = userLoginRequest.getUserRole();
        //2.查询用户
        String encryptPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", account);
        queryWrapper.eq("password", encryptPassword);
        queryWrapper.eq("user_role", userRole);
        User user = this.getOne(queryWrapper);
        if (user == null) {
            throw new CustomException("账号不存在或密码错误");
        }
        //查询出用户的头像
        QueryWrapper<Image> imageQueryWrapper = new QueryWrapper<>();
        imageQueryWrapper.eq("image_name_id", user.getUserId());
        imageQueryWrapper.eq("image_name", "userAvatar");
        if(imageMapper.selectOne(imageQueryWrapper)!=null){
            user.setUserAvatarUrl(imageMapper.selectOne(imageQueryWrapper).getImageUrl());
        }
        //3.检测用户状态
        if (user.getUserStatus() == 1) {
            throw new CustomException("账号已被封禁");
        }
        //4.记录用户信息
        request.getSession().setAttribute(user.getUserRole()+user.getAccount(), user);

        System.out.println("登录态1："+request.getSession().getAttribute(user.getUserRole()+user.getAccount()));

        //5.返回脱敏数据
        return BeanUtil.copyProperties(user, UserVO.class);
    }

    // 用户登出
    @Override
    public void userLogout(HttpServletRequest request, UserLogoutRequest userLogoutRequest) {
        System.out.println("key："+ userLogoutRequest.getUserRole()+ userLogoutRequest.getAccount());

//        //1. 判断是否登录
//        if (request.getSession().getAttribute(userLogoutRequest.getUserRole()+ userLogoutRequest.getAccount())==null) {
//            throw new  CustomException("未登录");
//        }
        //2. 移除登录态
        request.getSession().removeAttribute(userLogoutRequest.getUserRole()+ userLogoutRequest.getAccount());
        request.getSession().invalidate();
    }

    // 分页查询用户
    @Override
    public PageResponse<UserVO> pageUser(PageUserRequest pageUserRequest) {
        //1.获取参数
        String userRole = pageUserRequest.getUserRole();
        Integer userStatus = pageUserRequest.getUserStatus();
        String searchName = pageUserRequest.getSearchName();

        //2.构建分页条件
        Page<User> page = pageUserRequest.toPageDefaultSortByUpdateTime();

        //3.分页查询
        Page<User> userPage = lambdaQuery()
                .eq(StrUtil.isNotBlank(userRole), User::getUserRole, userRole)
                .eq(userStatus!=null, User::getUserStatus, userStatus)
                .and(StrUtil.isNotBlank(searchName),
                        w->w.like( User::getUserName, searchName)
                                .or()
                                .like(User::getAccount, searchName))
                .page(page);
        return PageResponse.of(userPage, UserVO.class);
    }

    // 更新用户信息
    @Override
    public boolean updateUserById(UserRequest userRequest) {
        //1.获取参数
        Long userId = userRequest.getUserId();
        String userName = userRequest.getUserName();
        String userAvatarUrl = userRequest.getUserAvatarUrl();
        String account = userRequest.getAccount();
        String userRole = userRequest.getUserRole();
        Integer userStatus = userRequest.getUserStatus();

        //2.更新用户信息
        QueryWrapper<Image> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("image_name_id", userId);
        queryWrapper.eq("image_name", "userAvatar");
        if(imageMapper.selectOne(queryWrapper)!=null){
            LambdaUpdateWrapper<Image> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Image::getImageNameId, userId)
                    .set(Image::getImageUrl, userAvatarUrl);
            imageMapper.update(null, updateWrapper);
        }else if(userAvatarUrl!=null) {
            Image  image =new Image();
            image.setImageName("userAvatar");//用户头像
            image.setImageNameId(userId);//类别ID
            image.setImageUrl(userAvatarUrl);
            imageMapper.insert(image);
        }
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getUserId, userId)
                .set(StrUtil.isNotBlank(userName), User::getUserName, userName)
                .set(StrUtil.isNotBlank(userAvatarUrl), User::getUserAvatarUrl, userAvatarUrl)
                .set(StrUtil.isNotBlank(account), User::getAccount, account)
                .set(StrUtil.isNotBlank(userRole), User::getUserRole, userRole)
                .set(userStatus!=null, User::getUserStatus, userStatus);
        return userMapper.update(null, updateWrapper)>0;
    }

    @Override
    public R<String> userUploadAvatar(Long userId,String imageUrl) {
        Image  image =new Image();
        image.setImageName("userAvatar");//用户头像
        image.setImageNameId(userId);//类别ID
        image.setImageUrl(imageUrl);
        imageMapper.insert(image);
        return R.success("上传成功",imageUrl);
    }

    @Override
    public void resetPassword(Long userId, String password) {
        //1.密码加密
        String encryptPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getUserId, userId)
                .set(User::getPassword, encryptPassword);
        userMapper.update(null, updateWrapper);
    }


}




